﻿using System;

namespace EpiNEXT.Core.Validation.Functions
{
    public class TextToDecimal : FunctionBase
    {
        public TextToDecimal()
            : base()
        {
        }

        public override object Execute(Record record, params object[] parameters)
        {
            DataEntryInstrument form = record.Form;

            string text = parameters[0].ToString();

            // detected a field value; pull from memory
            object fieldValue = record.GetFieldData(form.Fields[text]);
            if (fieldValue == null)
            {
                return null;
            }
            else if (fieldValue is decimal)
            {
                return (decimal)fieldValue;
            }
            else
            {
                decimal d;
                bool success = Decimal.TryParse(fieldValue.ToString(), out d);
                if (success)
                {
                    return d;
                }
                else
                {
                    return null;
                }
            }
            
        }
    }
}
